package com.kmproject.haifu.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.flyco.roundview.RoundTextView;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.widget.alertview.AlertView;
import com.jess.arms.widget.alertview.AlertViewOnItemClickListener;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.AppConstant;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ExtensionUtilKt;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerCustomRentingSeekingListComponent;
import com.kmproject.haifu.di.module.CustomRentingSeekingListModule;
import com.kmproject.haifu.mvp.contract.CustomRentingSeekingListContract;
import com.kmproject.haifu.mvp.model.entity.beans.RentSeekingDetail;
import com.kmproject.haifu.mvp.model.entity.beans.UserBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsCancelHouseRentSeekingCollection;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsListPage;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsQueryHoseRentSeekingList;
import com.kmproject.haifu.mvp.presenter.CustomRentingSeekingListPresenter;
import com.kmproject.haifu.mvp.ui.activity.ReleaseRentSeekingActivity;
import com.kmproject.haifu.mvp.ui.activity.RentSeekingDetailActivity;
import com.kmproject.haifu.mvp.ui.adapter.BaseRecyclerAdapter;
import com.kmproject.haifu.mvp.ui.holder.SmartViewHolder;
import com.kmproject.haifu.mvp.ui.widget.ExpandableTextView;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 求租
 */
public class CustomRentingSeekingListFragment extends BaseFragment<CustomRentingSeekingListPresenter> implements CustomRentingSeekingListContract.View {
    @BindView(R.id.srl_personal_hp_bis_data)
    PullToRefreshView srlPersonalHpBisData;
    @BindView(R.id.rv_personal_hp_bis_data)
    RecyclerView rvPersonalHpBisData;
    @BindView(R.id.i_empty)
    View empty;
    @BindView(R.id.rl_rent_seeking_list_bottom_layout)
    RelativeLayout rl_rent_seeking_list_bottom_layout;
    @BindView(R.id.cb_all_selected)
    CheckBox cb_all_selected;
    @BindView(R.id.rtv_delete_collection)
    RoundTextView rtv_delete_collection;
    private static final String TAB_FLAG = "tabFlag";
    private static final String USER_ID = "userId";
    private static final String BIS_TYPE = "bisType";
    private String userId;
    private int bisType;
    private UserBean userBean;//获取用户信息
    private boolean isInOperation = false;//操作管理中
    private List<Long> selectedIds;

    private BaseRecyclerAdapter<RentSeekingDetail> rentSeekingAdapter;
    private ReqParamsQueryHoseRentSeekingList reqParamsQueryHoseRentSeekingList;
    private ReqParamsListPage reqParamsListPage;

    /**
     * @param userId  userId为用户id；
     * @param bisType 账号类型：0-发布的求租列表；1-收藏的求租列表
     * @return
     */
    public static CustomRentingSeekingListFragment newInstance(String userId, int bisType) {
        CustomRentingSeekingListFragment fragment = new CustomRentingSeekingListFragment();
        Bundle args = new Bundle();
        args.putString(USER_ID, userId);
        args.putInt(BIS_TYPE, bisType);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerCustomRentingSeekingListComponent
                .builder()
                .appComponent(appComponent)
                .customRentingSeekingListModule(new CustomRentingSeekingListModule(this))//请将PersonalHpBisDataModule()第一个首字母改为小写
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_custom_renting_seeking_list, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        userBean = DataHelper.getDeviceData(getContext(), AppConstant.USER_INFO);//获取用户信息
        if (getArguments() != null) {
            userId = getArguments().getString(USER_ID);
            bisType = getArguments().getInt(BIS_TYPE);
        }

        rvPersonalHpBisData.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(0f).
                setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.common_menu_text)).setShowLastLine(false).build());
        ArmsUtils.configRecyclerView(rvPersonalHpBisData, new LinearLayoutManager(getContext()));
        rvPersonalHpBisData.setItemAnimator(new DefaultItemAnimator());
        srlPersonalHpBisData.setEnableRefresh(true);
        srlPersonalHpBisData.setEnableAutoLoadMore(false);
        srlPersonalHpBisData.setEnableHeaderTranslationContent(true);
        if (bisType == 1) {
            reqParamsListPage = new ReqParamsListPage();
            reqParamsListPage.setPage(1);
            reqParamsListPage.setLimit(AppConstant.pageSize);
        } else {
            reqParamsQueryHoseRentSeekingList = new ReqParamsQueryHoseRentSeekingList();
            reqParamsQueryHoseRentSeekingList.setPage(1);
            reqParamsQueryHoseRentSeekingList.setLimit(AppConstant.pageSize);
            reqParamsQueryHoseRentSeekingList.setUserId(userId);
        }
        rentSeekingAdapter = new BaseRecyclerAdapter<RentSeekingDetail>(R.layout.item_rent_seeking) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, RentSeekingDetail model, int position) {
                String category = model.getSeekingType();
                StringBuilder sb = new StringBuilder();
                if (!StringUtils.isEmpty(category)) {
                    switch (category) {
                        case "zz":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_0), model.getSeekingTypeName()))
                                    .append(".")
                                    .append(model.getRoomCountName()).append(model.getDrawingCountName()).append(model.getToiletCountName());
                            break;
                        case "hz":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_0), model.getSeekingTypeName()))
                                    .append(".")
                                    .append(ExtensionUtilKt.appendAcreage(Objects.requireNonNull(getContext()), model.getLowestAcreage(), model.getHighestAcreage()));
                            break;
                        case "bs":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                    .append(".")
                                    .append(model.getRoomCountName()).append(model.getDrawingCountName()).append(model.getToiletCountName());
                            break;
                        case "bgs":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                    .append(".")
                                    .append(ExtensionUtilKt.appendAcreage(Objects.requireNonNull(getContext()), model.getLowestAcreage(), model.getHighestAcreage()));
                            break;
                        case "sp":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                    .append(".")
                                    .append(ExtensionUtilKt.appendAcreage(Objects.requireNonNull(getContext()), model.getLowestAcreage(), model.getHighestAcreage()));
                            break;
                        case "cw":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_0), model.getSeekingTypeName()));
                            break;
                        case "cfck":
                            sb.append(String.format(getString(R.string.rent_seeking_detail_fm_1), model.getSeekingTypeName()))
                                    .append(".")
                                    .append(ExtensionUtilKt.appendAcreage(Objects.requireNonNull(getContext()), model.getLowestAcreage(), model.getHighestAcreage()));
                            break;
                    }
                }
                holder.text(R.id.tv_rent_seeking_base_info, sb);
                StringBuilder sbPrice = new StringBuilder();
                sbPrice.append(model.getLowestRentBudget()).append("-").append(model.getHighestRentBudget()).append(String.format(getString(R.string.rent_seeking_detail_fm_4), handUnit(model.getTenancy(), model.getEstimateRentingUnitName())));
                holder.text(R.id.tv_price, sbPrice);
                ExpandableTextView tv_detail_desc = (ExpandableTextView) holder.findViewById(R.id.tv_detail_desc);
                tv_detail_desc.setMaxLines(2);
                tv_detail_desc.setOriginalText(model.getDetailDesc());
                StringBuilder sbAddress = new StringBuilder();
                sbAddress.append(model.getParentSeekingAreaName()).append(model.getSeekingAreaName()).append(model.getPositionDescription());
                holder.text(R.id.tv_address, sbAddress);
                RelativeLayout rl_bottom_layout = (RelativeLayout) holder.findViewById(R.id.rl_bottom_layout);
                TextView tv_release_time = (TextView) holder.findViewById(R.id.tv_release_time);
                TextView tv_release_time_2 = (TextView) holder.findViewById(R.id.tv_release_time_2);
                tv_release_time.setText(String.format(getString(R.string.rent_seeking_detail_fm_5), model.getLatestTime()));
                tv_release_time_2.setText(String.format(getString(R.string.rent_seeking_detail_fm_5), model.getLatestTime()));

                RecyclerView rvRequirement = (RecyclerView) holder.findViewById(R.id.rv_house_requirement);
                if (model.getHouseRentDetailList() != null && model.getHouseRentDetailList().size() > 0) {
                    rvRequirement.setVisibility(View.VISIBLE);
                    rvRequirement.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(20f).
                            setHorizontalSpan(20f).setColor(ContextCompat.getColor(getContext(), R.color.white)).setShowLastLine(false).build());
                    ArmsUtils.configRecyclerView(rvRequirement, new GridLayoutManager(Objects.requireNonNull(getContext()), 4));
                    rvRequirement.setItemAnimator(new DefaultItemAnimator());

                    rvRequirement.setAdapter(new BaseRecyclerAdapter<RentSeekingDetail.HouseRentDetailListBean>(model.getHouseRentDetailList(), R.layout.item_release_room_feature) {
                        @Override
                        protected void onBindViewHolder(SmartViewHolder holder, RentSeekingDetail.HouseRentDetailListBean model, int position) {
                            RoundTextView textView = (RoundTextView) holder.findViewById(R.id.rtv_unique_feature);
                            textView.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.white));
                            textView.getDelegate().setStrokeWidth(1);
                            textView.getDelegate().setStrokeColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_F9D35A));
//                                textView.getDelegate().setBackgroundColor(ContextCompat.getColor(RentSeekingListActivity.this, R.color.color_F9D35A));
                            textView.setText(model.getBaseDictName());
                        }
                    });
                } else {
                    rvRequirement.setVisibility(View.GONE);
                }
                LinearLayout ll_bottom_operation = (LinearLayout) holder.findViewById(R.id.ll_bottom_operation);
                RoundTextView rtv_edit = (RoundTextView) holder.findViewById(R.id.rtv_edit);
                RoundTextView rtv_delete = (RoundTextView) holder.findViewById(R.id.rtv_delete);
                if (userBean != null && userBean.getUserId().equals(String.valueOf(model.getUserId()))) {
                    tv_release_time.setVisibility(View.GONE);
                    rl_bottom_layout.setVisibility(View.VISIBLE);
                    tv_release_time_2.setVisibility(View.VISIBLE);
                    ll_bottom_operation.setVisibility(View.VISIBLE);
                    rtv_edit.setOnClickListener(v -> {
                        Intent intent = new Intent(Objects.requireNonNull(getContext()), ReleaseRentSeekingActivity.class);
                        intent.putExtra("seekingId", String.valueOf(model.getSeekingId()));
                        ArmsUtils.startActivity(intent);
                    });
                    rtv_delete.setTag(position);
                    rtv_delete.setOnClickListener(v -> {
                        int tag = (int) v.getTag();
                        new AlertView(getString(R.string.note), getString(R.string.rent_seeking_delete_pmt), getString(R.string.cancel), new String[]{getString(R.string.sure_delete)}, null, Objects.requireNonNull(getContext()), AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                            @Override
                            public void onItemClick(Object o, int position) {
                                if (position != AlertView.CANCELPOSITION) {
                                    assert mPresenter != null;
                                    showLoading();
                                    mPresenter.deleteRentSeeking(String.valueOf(((RentSeekingDetail) rentSeekingAdapter.getItem(tag)).getSeekingId()));
                                }
                            }
                        }).show();
                    });
                } else {
                    tv_release_time.setVisibility(View.VISIBLE);
                    rl_bottom_layout.setVisibility(View.GONE);
                    ll_bottom_operation.setVisibility(View.GONE);
                    tv_release_time_2.setVisibility(View.GONE);
                }
                CheckBox checkBox = (CheckBox) holder.findViewById(R.id.cb_selected);
                checkBox.setTag(position);
                if (isInOperation) {
                    checkBox.setVisibility(View.VISIBLE);
                    if (selectedIds.contains(model.getSeekingId())) {
                        checkBox.setChecked(true);
                    } else {
                        checkBox.setChecked(false);
                    }
                    checkBox.setOnClickListener(v -> {
                        int pos = (int) v.getTag();
                        if (selectedIds != null) {
                            if (selectedIds.contains(rentSeekingAdapter.get(pos).getSeekingId())) {
                                selectedIds.remove(rentSeekingAdapter.get(pos).getSeekingId());
                            } else {
                                selectedIds.add(rentSeekingAdapter.get(pos).getSeekingId());
                            }
                            if (selectedIds.size() == rentSeekingAdapter.getCount()) {
                                cb_all_selected.setChecked(true);
                            } else {
                                cb_all_selected.setChecked(false);
                            }
                        }
                    });
//                    checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
//                        int pos = (int) buttonView.getTag();
//                        if (selectedIds != null) {
//                            if (selectedIds.contains(rentSeekingAdapter.get(pos).getSeekingId())) {
//                                selectedIds.remove(rentSeekingAdapter.get(pos).getSeekingId());
//                            } else {
//                                selectedIds.add(rentSeekingAdapter.get(pos).getSeekingId());
//                            }
//                        }
//                    });
                } else {
                    checkBox.setVisibility(View.GONE);
                }
            }
        };
        rvPersonalHpBisData.setAdapter(rentSeekingAdapter);

        rentSeekingAdapter.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = new Intent(getContext(), RentSeekingDetailActivity.class);
            intent.putExtra("seekingId", String.valueOf(((RentSeekingDetail) rentSeekingAdapter.getItem(position)).getSeekingId()));
            ArmsUtils.startActivity(intent);
        });

        srlPersonalHpBisData.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                if (bisType == 1) {
                    reqParamsListPage.setPage(curPageNo);
                } else {
                    reqParamsQueryHoseRentSeekingList.setPage(curPageNo);
                }
                sentSearchRentSeekingList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                if (bisType == 1) {
                    reqParamsListPage.setPage(curPageNo);
                } else {
                    reqParamsQueryHoseRentSeekingList.setPage(curPageNo);
                }
                sentSearchRentSeekingList();
            }
        });

        sentSearchRentSeekingList();
    }

    private String handUnit(String tenancy, String oldUnit) {
        if (tenancy.equals("short")) {//租期要求:short-短租，lasting-长租
            return getString(R.string.day_t);
        }
        return oldUnit;
    }

    private void setDeleteCollection() {
        if (isInOperation) {
            selectedIds = new ArrayList<>();
            rl_rent_seeking_list_bottom_layout.setVisibility(View.VISIBLE);
            cb_all_selected.setOnClickListener(v -> {
                if (selectedIds.size() < rentSeekingAdapter.getCount()) {
                    selectedAll();
                } else {
                    unSelectedAll();
                }
            });


            rtv_delete_collection.setOnClickListener(v -> {
                if (selectedIds != null && selectedIds.size() > 0) {
                    new AlertView(getString(R.string.note), getString(R.string.rent_seeking_delete_collection_pmt), getString(R.string.cancel), new String[]{getString(R.string.sure_delete)}, null, Objects.requireNonNull(getContext()), AlertView.Style.Alert, new AlertViewOnItemClickListener() {

                        @Override
                        public void onItemClick(Object o, int position) {
                            if (position != AlertView.CANCELPOSITION) {
                                assert mPresenter != null;
                                showLoading();
                                ReqParamsCancelHouseRentSeekingCollection reqParamsCancelHouseRentSeekingCollection = new ReqParamsCancelHouseRentSeekingCollection();
                                Long[] ids = new Long[selectedIds.size()];
                                for (int i = 0; i < ids.length; i++) {
                                    ids[i] = selectedIds.get(i);
                                }
                                reqParamsCancelHouseRentSeekingCollection.setSeekingIds(ids);
                                mPresenter.unCollectionSeeking(reqParamsCancelHouseRentSeekingCollection);
                            }
                        }
                    }).show();

                }
            });
        } else {
            rl_rent_seeking_list_bottom_layout.setVisibility(View.GONE);
        }
        rentSeekingAdapter.notifyDataSetChanged();
        rentSeekingAdapter.notifyListDataSetChanged();
    }

    private void unSelectedAll() {
        if (selectedIds != null) selectedIds.clear();
        if (rentSeekingAdapter != null) {
            rentSeekingAdapter.notifyDataSetChanged();
            rentSeekingAdapter.notifyListDataSetChanged();
        }
    }

    private void selectedAll() {
        if (rentSeekingAdapter == null || selectedIds == null) return;
        selectedIds.clear();
        for (RentSeekingDetail rsd : rentSeekingAdapter.getAllData()) {
            selectedIds.add(rsd.getSeekingId());
        }
        rentSeekingAdapter.notifyDataSetChanged();
        rentSeekingAdapter.notifyListDataSetChanged();
    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {
        if (data instanceof Boolean) {
            isInOperation = (boolean) data;
        }
        setDeleteCollection();
    }

    private void sentSearchRentSeekingList() {
        assert mPresenter != null;
        showLoading();
        if (bisType == 1) {
            mPresenter.getCollectionSeekingList(reqParamsListPage);
        } else {
            mPresenter.getRentSeekingList(reqParamsQueryHoseRentSeekingList);
        }
    }


    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
    }

    @Override
    public void getRentSeekingListSuccess(List<RentSeekingDetail> housePayWayBeans) {
        srlPersonalHpBisData.finishRefresh();
        srlPersonalHpBisData.finishLoadMore();
        if (housePayWayBeans != null && !housePayWayBeans.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rvPersonalHpBisData, true);
            if (ViewExtensionKt.isPullDown(srlPersonalHpBisData, housePayWayBeans.size(), reqParamsQueryHoseRentSeekingList.getLimit())) {
                rentSeekingAdapter.refresh(housePayWayBeans);
            } else {
                rentSeekingAdapter.loadMore(housePayWayBeans);
            }
        } else {
            if (reqParamsQueryHoseRentSeekingList.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rvPersonalHpBisData, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rvPersonalHpBisData, false);
            }
        }
    }

    @Override
    public void getListFailed() {
        if (reqParamsQueryHoseRentSeekingList != null) {
            if (reqParamsQueryHoseRentSeekingList.getPage() > 1) {
                reqParamsQueryHoseRentSeekingList.setPage(reqParamsQueryHoseRentSeekingList.getPage() - 1);
            }
        }
        srlPersonalHpBisData.finishLoadMore();
        srlPersonalHpBisData.finishRefresh();
    }

    @Override
    public void deleteRentSeekingSuccess() {
        hideLoading();
        sentSearchRentSeekingList();
    }

    @Override
    public void unCollectionSeekingSuccess() {
        hideLoading();
        sentSearchRentSeekingList();
    }

    @Override
    public void getCollectionSeekingListSuccess(List<RentSeekingDetail> rentSeekingDetailList) {
        srlPersonalHpBisData.finishRefresh();
        srlPersonalHpBisData.finishLoadMore();
        if (rentSeekingDetailList != null && !rentSeekingDetailList.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rvPersonalHpBisData, true);
            if (ViewExtensionKt.isPullDown(srlPersonalHpBisData, rentSeekingDetailList.size(), reqParamsListPage.getLimit())) {
                rentSeekingAdapter.refresh(rentSeekingDetailList);
            } else {
                rentSeekingAdapter.loadMore(rentSeekingDetailList);
            }
        } else {
            if (reqParamsListPage.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rvPersonalHpBisData, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rvPersonalHpBisData, false);
            }
        }
    }
}